package com.laifeng.sopcastsdk.local;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;

//import com.cy.helmet.Constant;
//import com.cy.helmet.HelmetApplication;
//import com.cy.helmet.connect.HelmetClient;
//import com.cy.helmet.core.protocol.Common;
//import com.cy.helmet.core.protocol.HelmetServer;
//import com.cy.helmet.core.protocol.MessageId;
//import com.cy.helmet.factory.FileMessageFactory;
//import com.cy.helmet.netty.RequestMessage;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by jiaqing on 2018/1/3.
 */

public class FileUtil {

    public static File getAudioDir() {
        File sdFile = Environment.getExternalStorageDirectory();
        File rootDir = new File(sdFile, "Helmet");
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }

        File recordDir = new File(rootDir, "Record");
        if (!recordDir.exists()) {
            recordDir.mkdir();
        }

        return recordDir;
    }

    public static File getAudioFile(String fileName) {
        return new File(getAudioDir(), fileName);
    }

    public static File getVideoDir() {
        File sdFile = Environment.getExternalStorageDirectory();
        File rootDir = new File(sdFile, "Helmet");
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }

        File recordDir = new File(rootDir, "Video");
        if (!recordDir.exists()) {
            recordDir.mkdir();
        }

        return recordDir;
    }

    public static File getPhotoDir() {
        File sdFile = Environment.getExternalStorageDirectory();
        File rootDir = new File(sdFile, "Helmet");
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }

        File recordDir = new File(rootDir, "Photo");
        if (!recordDir.exists()) {
            recordDir.mkdir();
        }

        return recordDir;
    }

    public static File saveAudioMessage(String uuid, byte[] bytes) {
        File audioDir = getAudioDir();
        File receiveAudioFile = new File(audioDir, "receive_audio_file.mp3");

        FileOutputStream outputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            if (receiveAudioFile.exists()) {
                receiveAudioFile.delete();
            }
            receiveAudioFile.createNewFile();
            outputStream = new FileOutputStream(receiveAudioFile);
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            bufferedOutputStream.write(bytes);
            bufferedOutputStream.flush();

            return receiveAudioFile;

        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
        } finally {
            // 关闭创建的流对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }

        return null;
    }

    private long getTotalSize() {
        if (isSDCardAvaliable()) {
            File file = Environment.getExternalStorageDirectory();
            StatFs statFs = new StatFs(file.getPath());

            //获得sdcard上 block的总数
            long blockCount = statFs.getBlockCount();
            //获得sdcard上每个block 的大小
            long blockSize = statFs.getBlockSize();
            //计算标准大小使用：1024，当然使用1000也可以
            long bookTotalSize = blockCount * blockSize;
            return bookTotalSize;
        } else {
            return -1;
        }
    }

    public static long getAvailableSize() {
        if (isSDCardAvaliable()) {
            File file = Environment.getExternalStorageDirectory();
            StatFs statFs = new StatFs(file.getPath());

            //获得Sdcard上每个block的size
            long blockSize = statFs.getBlockSize();
            //获取可供程序使用的Block数量
            long blockavailable = statFs.getAvailableBlocks();
            //计算标准大小使用：1024，当然使用1000也可以
            long blockavailableTotal = blockSize * blockavailable;
            return blockavailableTotal;
        } else {
            return -1;
        }
    }

    public static boolean isSDCardAvaliable() {
        return true;
    }

//    public static void deleteFile(int fileType, String fileName) {
//        File deleteFile = null;
//        if (fileType == Constant.FILE_TYPE_VIDEO) {
//            deleteFile = new File(FileUtil.getVideoDir(), fileName);
//        } else if (fileType == Constant.FILE_TYPE_PHOTO) {
//            deleteFile = new File(FileUtil.getPhotoDir(), fileName);
//        }
//
//        boolean delSuccess = false;
//        if (deleteFile != null && deleteFile.exists()) {
//            delSuccess = deleteFile.delete();
//        }
//
//        LogUtil.e("delete: " + fileName + ":" + delSuccess);
//
//        HelmetServer.H2SMessage msg = FileMessageFactory.getFileDelRespMessage(fileName, delSuccess);
//        RequestMessage request = new RequestMessage(msg);
//        HelmetClient.currentClient().senMessage(request);
//    }

    public static void saveBitmapFromYuvImage(Bitmap bitmap) {
        if (bitmap != null) {
            //rotate bitmap
            Matrix matrix = new Matrix();
            matrix.preRotate(90);
            Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle();
            saveBitmap(rotatedBitmap);
        }
    }


    public static void saveBitmap(Bitmap bmp) {

        File photoFile = getEmptyPhotoFile();
        Log.e("YJQ", "saving Bitmap : " + photoFile.getName());

        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            fos = new FileOutputStream(photoFile);
            bos = new BufferedOutputStream(fos);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
        } catch (IOException e) {
            Log.e("YJQ", "Err when saving bitmap...");
            e.printStackTrace();
            return;
        } finally {
            if (bmp != null && !bmp.isRecycled()) {
                bmp.recycle();
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static File getEmptyPhotoFile() {
        File photoDir = getPhotoDir();
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = formater.format(new Date()) + ".png";

        return new File(photoDir, fileName);
    }
}
